﻿using System;
using System.Reflection;

public static partial class Extensions
{
    /// <summary>
    /// 浅拷贝
    /// </summary>
    public static T CloneShallow<T>(this T obj)
    {
        if (obj is string || obj.GetType().IsValueType) return obj;
        object retval = Activator.CreateInstance(obj.GetType());
        FieldInfo[] fields = obj.GetType().GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance);
        foreach (var field in fields)
        {
            try
            {
                field.SetValue(retval, field.GetValue(obj));
            }
            catch { }
        }
        return (T)retval;
    }

    /// <summary>
    /// 深拷贝 TODO 暂时有bug
    /// </summary>
    public static T CloneDeep<T>(this T obj)
    {
        //if (obj is string || obj.GetType().IsValueType) return obj;
        //object retval = Activator.CreateInstance(obj.GetType());
        //FieldInfo[] fields = obj.GetType().GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance);
        //foreach (var field in fields)
        //{
        //    try
        //    {
        //        field.SetValue(retval, CloneDeep(field.GetValue(obj)));
        //    }
        //    catch { }
        //}
        //return (T)retval;
        return obj.ToJson().ToObject<T>();
    }
}